import { fetch } from 'dva';
import { message } from 'antd';

var tenantId = localStorage.getItem('tenantId');
tenantId = tenantId == '0' ? '1' : tenantId;
const UploadUtil = {
  actionURL: '/api/UploadFilesAsync',
  uploadOSS: '/api/UploadOSS',
  ossServDefault: 'https://operp-tenant-1.oss-cn-shanghai.aliyuncs.com/',
  ossServ: 'https://operp-tenant-' + tenantId + '.oss-cn-shanghai.aliyuncs.com/',
  imgServ: '/api/GetImageAsync?tenantId=' + tenantId + '&sysRowId=',
  pdfServ: '/api/GetPdfAsync?tenantId=' + tenantId + '&sysRowId=',
  getOssFile: '/api/GetOSSFile?tenantId=' + tenantId + '&sysRowId=',
  QRCodeServer: '/api/GetQRCode',
  accessToken: 'Bearer ' + localStorage.getItem('access-token'),
  uploadPic: async function (files, objectId, objectName, objectField) {
    let formData = new FormData();
    files.forEach((element) => {
      formData.append('files', element.originFileObj);
    });
    formData.append('objectId', objectId);
    formData.append('objectName', objectName);
    formData.append('objectField', objectField);

    var resp = {};
    await fetch(this.actionURL, {
      method: 'POST',
      headers: {
        Authorization: this.accessToken,
      },
      body: formData,
    })
      .then((response) => response.json())
      .then((responseData) => {
        resp = responseData;
      })
      .catch(() => {
        message.error('图片上传失败');
      });
    if (resp && resp.success) {
      return resp.result;
    } else {
      return '';
    }
  },
  getBase64: function (img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  },
  beforeUpload: function (file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('仅限于 JPG/PNG 文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 5;
    if (!isLt2M) {
      message.error('文件大小不得大于 5MB!');
    }
    return isJpgOrPng && isLt2M;
  },
  checkExcel: function (file) {
    const isAllow = file.type === 'application/vnd.ms-excel';
    if (!isAllow) {
      message.error('仅限于 Excel 文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 5;
    if (!isLt2M) {
      message.error('文件大小不得大于 5MB!');
    }
    return isAllow && isLt2M;
  },
  checkPdf: function (file) {
    const isAllow = file.type === 'application/pdf';
    if (!isAllow) {
      message.error('仅限于 PDF 文件!');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 5;
    if (!isLt2M) {
      message.error('文件大小不得大于 5MB!');
      return false;
    }
    return true;
  },
};

export default UploadUtil;
